/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.frontEnd;


import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.enumIdCreator.EnumIdCreator;
import org.jespxml.JespXML;
import org.jespxml.modelo.Atributo;
import org.jespxml.modelo.CData;
import org.jespxml.modelo.Tag;
import org.jxmllanguage.model.Component;
import org.xml.sax.SAXException;

/**
 *
 * @author Patricio Pérez Pinto
 */
public class XJxmlLanguage extends javax.swing.JFrame {
    private List<Component> componentes;

    /**
     * Creates new form XJxmlLanguage
     */
    public XJxmlLanguage() {
        initComponents();
        initJFileChooser();
        this.setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        open = new javax.swing.JFileChooser();
        save = new javax.swing.JFileChooser();
        jLabel1 = new javax.swing.JLabel();
        nombreIdioma = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        tabConte = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        idiomaOriginal = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        idiomaNuevo = new javax.swing.JTextArea();
        palabrasOriginal = new javax.swing.JLabel();
        palabrasNuevo = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ayuda = new javax.swing.JTextArea();
        jButton3 = new javax.swing.JButton();

        open.setApproveButtonText("Abrir");
        open.setApproveButtonToolTipText("");

        save.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
        save.setApproveButtonText("Elegir ruta");
        save.setApproveButtonToolTipText("");
        save.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("JXmlLanguage GUI");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Nombre idioma:");

        jButton2.setText("Rescatar palabras desde formulario .java");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setText("Idioma original");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel3.setText("Traducción");

        idiomaOriginal.setColumns(20);
        idiomaOriginal.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        idiomaOriginal.setRows(5);
        idiomaOriginal.setTabSize(4);
        idiomaOriginal.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                idiomaOriginalKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                idiomaOriginalKeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(idiomaOriginal);

        idiomaNuevo.setColumns(20);
        idiomaNuevo.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        idiomaNuevo.setRows(5);
        idiomaNuevo.setTabSize(4);
        idiomaNuevo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                idiomaNuevoKeyReleased(evt);
            }
        });
        jScrollPane3.setViewportView(idiomaNuevo);

        palabrasOriginal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        palabrasOriginal.setText("0");

        palabrasNuevo.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        palabrasNuevo.setText("0");

        jLabel4.setText("Palabras:");

        jLabel5.setText("Palabras:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(palabrasOriginal, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(222, 222, 222)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(palabrasNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(palabrasOriginal)
                    .addComponent(palabrasNuevo)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addContainerGap())
        );

        tabConte.addTab("JXmlLanguage", jPanel1);

        ayuda.setEditable(false);
        ayuda.setColumns(20);
        ayuda.setRows(5);
        ayuda.setText("Todas las palabras agregadas quedarán en un archivo xml. Tambien para su\nayuda, se ha creado un archivo llamado Id.java. A continuación se muestra\nun ejemplo para poder utilizar JXmlLanguage: ");
        jScrollPane1.setViewportView(ayuda);

        tabConte.addTab("Ayuda", jScrollPane1);

        jButton3.setText("Generar XML e Id.java");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tabConte)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 271, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nombreIdioma)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nombreIdioma, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tabConte)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int op = open.showOpenDialog(this);
        if (op == JFileChooser.APPROVE_OPTION) {
            FileInputStream fis = null;
            try {
                File f = open.getSelectedFile();
                fis = new FileInputStream(f);
                BufferedReader leer =
                        new BufferedReader(new InputStreamReader(fis));
                String line;
                componentes = new ArrayList<>();
                String id;
                while (leer.ready()) {
                    line = leer.readLine();
                    if (line.contains("setText")) {
                        id = getId(line);
                        if (id != null) {
                            if (!isComponente(id) && !id.equalsIgnoreCase("")) {//para no poner dos txt repetidos
                                componentes.add(new Component(id));
                            }
                        }
                    }
                }

                String uri = "http://translate.google.es/#es/en/";
                String txt = "";
                Collections.sort(componentes);
                for (Component c : componentes) {
                    System.out.println(c.getId());
                    txt += c.getId() + "\n"; 
                }
                txt = txt.substring(0,txt.length() -1);
                Desktop.getDesktop().browse(new URI(uri));
                this.palabrasOriginal.setText(String.valueOf(componentes.size()));
                idiomaOriginal.setText(txt);
                JOptionPane.showMessageDialog(this, "Ahora pegue las frases traducidas en la parte \"Traducción\"");
            } catch (    URISyntaxException | IOException ex) {
                Logger.getLogger(XJxmlLanguage.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(XJxmlLanguage.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        String palOri, palNue;
        palOri = palabrasOriginal.getText();
        palNue = palabrasNuevo.getText();

        if(!idiomaOriginal.getText().trim().equalsIgnoreCase("")){
            if(palOri.equalsIgnoreCase(palNue)){
                int op = save.showSaveDialog(this);

                if(op == JFileChooser.APPROVE_OPTION){
                    componentes = new ArrayList<>();
                    String[] pOriginal, pNuevo;
                    pOriginal = idiomaOriginal.getText().split("\n");
                    pNuevo = idiomaNuevo.getText().split("\n");

                    for(int i=0; i<pOriginal.length; i++){
                        componentes.add(new Component(pOriginal[i].replaceAll(" ", "_").toUpperCase(), pNuevo[i]));
                    }

                    if(nombreIdioma.getText().trim().equalsIgnoreCase("")){
                        nombreIdioma.setText("language");
                    }

                    generarXML(save.getSelectedFile());
                }


            }else{
                JOptionPane.showMessageDialog(this, "Deben ser la misma cantidad de palabras en ambos lados", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        
        
    }//GEN-LAST:event_jButton3ActionPerformed

    private void idiomaNuevoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_idiomaNuevoKeyReleased
        String[] str = idiomaNuevo.getText().split("\n");
        palabrasNuevo.setText(String.valueOf(str.length));
    }//GEN-LAST:event_idiomaNuevoKeyReleased

    private void idiomaOriginalKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_idiomaOriginalKeyReleased
        String[] str = idiomaOriginal.getText().split("\n");
        palabrasOriginal.setText(String.valueOf(str.length));
        
    }//GEN-LAST:event_idiomaOriginalKeyReleased

    private void idiomaOriginalKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_idiomaOriginalKeyPressed
//        if(evt.getKeyCode() == KeyEvent.VK_TAB){
//            idiomaNuevo.requestFocus();
//        }
    }//GEN-LAST:event_idiomaOriginalKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(
                    javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(XJxmlLanguage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new XJxmlLanguage().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea ayuda;
    private javax.swing.JTextArea idiomaNuevo;
    private javax.swing.JTextArea idiomaOriginal;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField nombreIdioma;
    private javax.swing.JFileChooser open;
    private javax.swing.JLabel palabrasNuevo;
    private javax.swing.JLabel palabrasOriginal;
    private javax.swing.JFileChooser save;
    private javax.swing.JTabbedPane tabConte;
    // End of variables declaration//GEN-END:variables

    private void initJFileChooser() {
        open.addChoosableFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                return (f.getName().contains(".java") || f.isDirectory());
            }

            @Override
            public String getDescription() {
                return "*.java (Formulario)";
            }
        });
        open.setAcceptAllFileFilterUsed(false);
    }

    /*método creado para rescatar el texto de la linea "setText"*/
    private String getId(String line) {
        line = line.trim();
        line = line.replace("(", ";");
        line = line.replace(")", ";");
        
        String contenidoSetText = line.split(";")[1];
        if(contenidoSetText.contains("\"")){
            try{
                contenidoSetText = contenidoSetText.split("\"")[1];
                if(isNumber(contenidoSetText)){
                    return null;
                }else{
                    String pn =getPalabraNormalizada(contenidoSetText);
                    if(pn.equalsIgnoreCase("")){
                        return null;
                    }
                    return pn.trim();
                }
            }catch(ArrayIndexOutOfBoundsException ex){
                //cae acá si el settext esta Asi: setText("");
            }
        }
        
        return null;//el contenido es null cuando el texto es un numero, o es vacio
    }

    private boolean isComponente(String id) {
        for(Component c : componentes){
            if(c.getId().equalsIgnoreCase(id)){
                return true;
            }
        }
        return false;
    }

    private boolean isNumber(String txt){
        try{
            Integer.parseInt(txt);
            return true;
        }catch(NumberFormatException ex){
            return false;
        }
    }
    
    private String getPalabraNormalizada(String palabra){
//        palabra = palabra.replaceAll("ñ", "n");
        palabra = palabra.replaceAll("á", "a");
        palabra = palabra.replaceAll("é", "e");
        palabra = palabra.replaceAll("í", "i");
        palabra = palabra.replaceAll("ó", "o");
        palabra = palabra.replaceAll("ú", "u");
        
        palabra = palabra.replaceAll("Á", "a");
        palabra = palabra.replaceAll("É", "e");
        palabra = palabra.replaceAll("Í", "i");
        palabra = palabra.replaceAll("Ó", "o");
        palabra = palabra.replaceAll("Ú", "u");
        
        palabra = palabra.replaceAll(":", "");
        palabra = palabra.replaceAll(";", "");
        palabra = palabra.replaceAll("'", "");
        palabra = palabra.replaceAll("%", "");
        palabra = palabra.replaceAll("!", "");
        palabra = palabra.replaceAll("¡", "");
        palabra = palabra.replaceAll("<", "");
        palabra = palabra.replaceAll(">", "");
        palabra = palabra.replaceAll(",", " ");
        palabra = palabra.replaceAll("=", "");
        palabra = palabra.replaceAll("-", "");
        palabra = palabra.replaceAll("\\+", "");
        palabra = palabra.replaceAll("\\\\", "");
        palabra = palabra.replaceAll("/", "");
        palabra = palabra.replaceAll("#", "");
        palabra = palabra.replaceAll("\\.", " ");
        return palabra;
    }

    private void generarXML(File file) {
        try {
            Tag raiz = new Tag("language");
            raiz.addAtributo(new Atributo("name", nombreIdioma.getText().trim()));
            
//            new File("language"+File.separator+"autogen").mkdirs();
            
            Tag component;
            for(Component c : componentes){
                component = new Tag("component");
                component.addAtributo(new Atributo("id", c.getId()));
                component.setValorCdata(new CData(c.getValue()));
                raiz.addTagHijo(component);
            }
            
//            JespXML ar = new JespXML("language"+File.separator+"autogen"+File.separator+"language.xml");
            JespXML ar = new JespXML(file.getPath()+File.separator+nombreIdioma.getText().trim().replaceAll(" ", "_") +".xml");
            ar.escribirXML(raiz);
            generarIDJava(file);
        } catch (ParserConfigurationException | FileNotFoundException | TransformerException ex) {
            Logger.getLogger(XJxmlLanguage.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }

    private void generarIDJava(File file) {
        try {
            String[] args = new String[6];
            args[0] = "-x";
            args[1] = "\""+file.getPath()+File.separator+nombreIdioma.getText().trim().replaceAll(" ", "_")+".xml\"";
            args[2] = "-p";
            args[3] = "org.language";
            args[4] = "-o";
            args[5] = "\""+file.getPath()+File.separator+"\"";
            
            EnumIdCreator.main(args);
            Desktop.getDesktop().browse(file.toURI());
            ayuda.setText(ayuda.getText()+"\n\ttry {\n"
                    + "            Language lan = new Language(\""+file.getPath()+File.separator+nombreIdioma.getText().trim().replaceAll(" ", "_") +".xml"+"\");\n"
                    + "            String valor = lan.getValueById(\"nombreDelId\"); //y obtendras el valor del idioma nuevo\n"
                    + "            // o puedes hacerlo con la clase Id.java generada\n"
                    + "            valor = lan.getValorById(Id.nombreDelId);\n"
                    + "        } catch (ValueNotFoundException ex) {\n"
                    + "            Logger.getLogger(PruebaJXMLLanguage.class.getName()).log(Level.SEVERE, null, ex);\n"
                    + "        }  catch (IOException | MalformedXMLLanguegeException ex) {\n"
                    + "            Logger.getLogger(Language.class.getName()).log(Level.SEVERE, null, ex);\n"
                    + "        }");
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            Logger.getLogger(XJxmlLanguage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}
